<template>
  <div>
    <!-- 头部区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-alert
        title="注意:只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      ></el-alert>
      <el-row class="options">
        <el-col>
          <span>选择商品分类</span>
          <el-cascader
            v-model="selectedID"
            :options="cateList"
            @change="handleChange"
            expand-trigger="hover"
            :props="cateOption"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isbtnDisabled"
            size="mini"
            @click="dialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数详情面板 -->
          <el-table :data="dymList" style="width: 100%" border stripe>
            <el-table-column type="expand" width="180">
              <template slot-scope="scope">
                <!-- 循环生成 Tag 标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
              width="180"
            ></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDia(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletePara(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isbtnDisabled" size="mini" @click="dialogVisible = true">添加属性</el-button
          >
          <!-- 静态属性面板 -->
          <el-table :data="staticList" style="width: 100%" border stripe>
             <el-table-column type="expand" width="180">
              <template slot-scope="scope">
                <!-- 循环生成 Tag 标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i"  @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                class="input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#"
              width="180"
            ></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDia(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletePara(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="dialogVisible" width="50%" @close="addDiaClosed">
      <el-form :model="addForm" :rules="addrules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="editDiaClosed">
      <el-form :model="editForm" :rules="editrules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmedit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      selectedID: [],
      activeName: "many",
      btnFlag: "true",
      dymList: [],
      staticList: [],
      dialogVisible: false,
      //控制修改面板的显示
      editDialogVisible: false,
      editForm:{
      },
      editrules: {
        attr_name: [
          { required: true, message: '请输入', trigger: 'blur' },
        ]
      },
      addForm: {
        attr_name: ''
      },
      addrules: {
        attr_name: [
          { required: true, message: '请输入', trigger: 'blur' },
        ]
      },
      //级联选择框的配置对象
      cateOption: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取列表参数失败");
      this.$message.success("获取参数列表成功");
      this.cateList = res.data;
      console.log(this.cateList);
    },
    //监听级联菜单里的选项变化
    handleChange() {
      this.getParamsData();
    },
    handleTabClick() {
      console.log(this.activeName);
      this.getParamsData();
    },
    async getParamsData() {
      console.log(this.selectedID);
      if (this.selectedID.length !== 3) {
        this.selectedID = [];
        this.dymList = [],
        this.staticList = []
        return 
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals ? element.attr_vals.split(' '): []
        //在每一项的数据中 加 两个属性(inputvisible 和 inputvalue)
        //控制文本框的显示与隐藏
        element.inputVisible = false
        //文本框中输入的值
        element.inputValue = ''
      });
      console.log(res, this.cateID);
      if (this.activeName == "only") {
        this.staticList = res.data;
      } else {
        this.dymList = res.data;
      }
    },
    addDiaClosed(){
      this.$refs.addFormRef.resetFields()
    },
    confirmAdd() {
      this.$refs.addFormRef.validate(async val => {
        if(!val) return
        const {data: res} = await this.$http.post(`categories/${this.cateID}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName 
      })
        if(res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.dialogVisible = false
        this.getParamsData()
        console.log(res, this.activeName);
      }
    )
    },
    //展示修改按钮对话框
    async showEditDia(id) {
      //根据 id 查询对应参数的属性值
      const {data: res} = await this.$http.get(`categories/${this.cateID}/attributes/${id}`, {
       params: { attr_sel: this.activeName }
      })
      // if(res.meta.status !== 200) return this.$message.error('获取信息失败') 
      this.editForm = res.data
      this.editDialogVisible = true
      // console.log(this.activeName);
    },
    //监听展示修改对话框关闭事件,重置表单
    editDiaClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 确定修改参数面板
    confirmedit() {
      this.$refs.editFormRef.validate(async val => {
        if(!val) return this.$message.error('请输入合法内容')
        const {data: res} = await this.$http.put(`categories/${this.cateID}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
        })
        if(res.meta.status !==200) return this.$message.error('更新参数失败')
        this.$message.success('更新成功')
        this.getParamsData()
        this.editDialogVisible = false
      })
    },
    async deletePara(id) {
      const {data: res} = await this.$http.delete(`categories/${this.cateID}/attributes/${id}`)
      if(res.meta.status !== 200) return this.$message.error('删除属性失败') 
      this.$message.success('删除成功')
      this.getParamsData()
      this.editDialogVisible = false
    },
    async handleInputConfirm (role) {
      //如果没有输入内容
      if(role.inputValue.trim().length == 0) {
        role.inputValue = '',
        role.inputVisible = false
        return 
      }
      role.attr_vals.push(role.inputValue)
      role.inputValue = ''
      role.inputVisible = false
      //需要发起请求,保存添加的数据
      this.saveAttr_vals(role)
    },
    showInput (role) {
      role.inputVisible = true
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async saveAttr_vals(role) {
      const {data: res} = await this.$http.put(`categories/${this.cateID}/attributes/${role.attr_id}`, {
        attr_name: role.attr_name,
        attr_sel: role.attr_sel,
        attr_vals: role.attr_vals.join(' ')
      })
      console.log(res);
      if(res.meta.status !== 200) {
        return this.$message.error('修改参数失败')
      }
      this.$message.success('修改参数成功')
    }
    ,
    //删除对应的参数选项
    handleClose (index, role) {
      role.attr_vals.splice(index, 1)
      this.saveAttr_vals(role)
    }
  },
  computed: {
    //如果按钮需要被禁用,就返回true, 否则返回 false
    isbtnDisabled() {
      return this.selectedID.length !== 3 ? true : false;
    },
    cateID() {
      if (this.selectedID.length === 3) {
        return this.selectedID[2];
      } else {
        return null;
      }
    },
    titleText() {
      if(this.activeName == 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    },
    

  },
};
</script>


<style lang="less" scoped>
.options {
  margin-top: 15px;
}

.el-tag {
  margin: 0 10px;
}

.input-new-tag {
  width: 120px;
}
</style>
